package dao

import (
	"tapay-ws/global"
	"tapay-ws/internal/model"
	"time"
)

func (d *Dao) CreateUserOnline(obj model.UserOnline) error {
	online := model.UserOnline{Uid: obj.Uid, UserType: obj.UserType, Status: global.StatusOnline}
	cnt, err := online.Count(d.engine)
	if err != nil {
		return err
	}
	if cnt > 0 {
		return nil
	}
	online.Status = global.StatusNull
	offline, err := online.LastOne(d.engine)
	if err != nil {
		return err
	}
	if offline != nil && int64(offline.EndTime) >= time.Now().Unix()-global.AppSetting.ConnTimeDiff {
		return offline.RefreshOnline(d.engine)
	}
	return obj.Create(d.engine)
}

func (d *Dao) UpdateUserOffline(uid uint32, userType uint8) error {
	obj := model.UserOnline{Uid: uid, UserType: userType}
	return obj.UpdateOffline(d.engine)
}
